package com.example.controller;

import com.example.entity.Friend;
import com.example.entity.User;
import com.example.interceptor.TokenNotValidation;
import com.example.response.R;
import com.example.service.FriendService;
import com.example.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/friend")
public class FriendController {

    @Autowired
    FriendService friendService;

    /**
     * 新增好友
     *
     * @param friendUid
     * @param request
     */
    @TokenNotValidation
    @PutMapping("/insertFriend/{friendUid}")
    public R insertFriend(@PathVariable Integer friendUid, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        token = token.substring(7);
        Integer userId = JwtUtil.getUserId(token);
        Friend friend = new Friend();
        friend.setFriendUid(friendUid);
        friend.setUid(userId);
        Boolean aBoolean = friendService.checkIsAdd(friendUid, userId);
        if (userId == friendUid) {
            return R.fail(501, "请不要添加自己，蟹蟹您嘞");
        }
        if (aBoolean) {
            return R.fail(501, "您已添加过该好友");
        } else {
            friendService.insert(friend);
            return R.success();
        }
    }

    @TokenNotValidation
    @GetMapping("/getMyFriend")
    public List<User> getMyFriend(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        token = token.substring(7);
        Integer userId = JwtUtil.getUserId(token);
        return friendService.selectMyFriend(userId);
    }

}
